package com.huanglj.himalaya.data.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.huanglj.himalaya.base.BaseApplication;
import com.huanglj.himalaya.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.model.album.Announcer;
import com.ximalaya.ting.android.opensdk.model.track.Track;

import java.util.ArrayList;
import java.util.List;

import static com.huanglj.himalaya.utils.Constants.HISTORY_AUTHOR_NAME;
import static com.huanglj.himalaya.utils.Constants.HISTORY_COVER;
import static com.huanglj.himalaya.utils.Constants.HISTORY_DESCRIPTION;
import static com.huanglj.himalaya.utils.Constants.HISTORY_DURATION;
import static com.huanglj.himalaya.utils.Constants.HISTORY_ID;
import static com.huanglj.himalaya.utils.Constants.HISTORY_PLAY_COUNT;
import static com.huanglj.himalaya.utils.Constants.HISTORY_TB_NAME;
import static com.huanglj.himalaya.utils.Constants.HISTORY_TITLE;
import static com.huanglj.himalaya.utils.Constants.HISTORY_TRACK_ID;
import static com.huanglj.himalaya.utils.Constants.HISTORY_UPDATE_TIME;

public class HistoryDao implements IHistoryDao {

    private static final String TAG = "HistoryDao";
    private IHistoryDaoCallBack mCallBack;
    private final XimalayaDBHelper mXimalayaDBHelper;
    private List<Track> result = new ArrayList<>();

    public static HistoryDao getInstance() {
        return ourInstance;
    }

    private static final HistoryDao ourInstance = new HistoryDao();

    private HistoryDao() {
        mXimalayaDBHelper = new XimalayaDBHelper(BaseApplication.getContext());
    }

    @Override
    public void addTracks(Track track) {
        SQLiteDatabase db = null;
        boolean isSuccess = false;
        try {
            db = mXimalayaDBHelper.getReadableDatabase();
            db.beginTransaction();
            db.delete(HISTORY_TB_NAME,HISTORY_TRACK_ID + "=?",new String[]{track.getDataId()+""});
            ContentValues contentValues = new ContentValues();
            contentValues.put(HISTORY_TRACK_ID,track.getDataId());
            contentValues.put(HISTORY_TITLE,track.getTrackTitle());
            contentValues.put(HISTORY_COVER,track.getCoverUrlLarge());
            contentValues.put(HISTORY_PLAY_COUNT,track.getPlayCount());
            contentValues.put(HISTORY_AUTHOR_NAME,track.getAnnouncer().getNickname());
            contentValues.put(HISTORY_UPDATE_TIME,track.getUpdatedAt());
            contentValues.put(HISTORY_DURATION,track.getDuration());
            db.insert(HISTORY_TB_NAME,null,contentValues);
            db.setTransactionSuccessful();
            isSuccess = true;
        }catch (Exception e){
            isSuccess = false;
            e.printStackTrace();
        }finally {
            db.endTransaction();
            db.close();
            if (mCallBack != null) {
                mCallBack.onHistoryAdd(isSuccess);
            }
        }
    }

    @Override
    public void deleteTracks(Track track) {
        SQLiteDatabase db = null;
        boolean isSuccess = false;
        try {
            db = mXimalayaDBHelper.getReadableDatabase();
            db.beginTransaction();
            int delete = db.delete(HISTORY_TB_NAME, HISTORY_TRACK_ID + "=?", new String[]{track.getDataId() + ""});
            LogUtil.d(TAG,"deleteResult: "+delete);
            db.setTransactionSuccessful();
            isSuccess = true;
        }catch (Exception e){
            isSuccess = false;
            e.printStackTrace();
        }finally {
            db.endTransaction();
            db.close();
            if (mCallBack != null) {
                mCallBack.onHistoryDelete(isSuccess);
            }
        }
    }

    @Override
    public void getHistoryList() {
        SQLiteDatabase db = null;
        try{
            db = mXimalayaDBHelper.getReadableDatabase();
            db.beginTransaction();
            result.clear();
            Cursor query = db.query(HISTORY_TB_NAME, null, null, null, null, null, "_id desc");
            while (query.moveToNext()) {
                Track track = new Track();
                int historyId = query.getInt(query.getColumnIndex(HISTORY_TRACK_ID));
                track.setDataId(historyId);
                String trackTitle = query.getString(query.getColumnIndex(HISTORY_TITLE));
                track.setTrackTitle(trackTitle);
                String trackCover = query.getString(query.getColumnIndex(HISTORY_COVER));
                track.setCoverUrlLarge(trackCover);
                int trackPlayCount = query.getInt(query.getColumnIndex(HISTORY_PLAY_COUNT));
                track.setPlayCount(trackPlayCount);
                long trackUpdateTime = query.getLong(query.getColumnIndex(HISTORY_UPDATE_TIME));
                track.setUpdatedAt(trackUpdateTime);
                int trackDuration = query.getInt(query.getColumnIndex(HISTORY_DURATION));
                String authorName = query.getString(query.getColumnIndex(HISTORY_AUTHOR_NAME));
                Announcer announcer = new Announcer();
                announcer.setNickname(authorName);
                track.setAnnouncer(announcer);
                track.setDuration(trackDuration);
                result.add(track);
            }
            db.setTransactionSuccessful();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            db.endTransaction();
            db.close();
            if (mCallBack != null) {
                mCallBack.onHistoryList(result);
            }
        }

    }

    @Override
    public void clearHistory() {
        SQLiteDatabase db = null;
        try{
            db = mXimalayaDBHelper.getReadableDatabase();
            db.beginTransaction();
            db.delete(HISTORY_TB_NAME,null,null);
            db.setTransactionSuccessful();
            result.clear();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            db.endTransaction();
            db.close();
            if (mCallBack != null) {
                mCallBack.onHistoryClear();
            }
        }
    }

    @Override
    public void unRegisterViewCallBack(IHistoryDaoCallBack iHistoryDaoCallBack) {

    }

    @Override
    public void registerViewCallBack(IHistoryDaoCallBack iHistoryDaoCallBack) {
        mCallBack = iHistoryDaoCallBack;
    }
}
